#include "WProgram.h"
#include "WConstants.h"
#include "SerialLCD.h"

#include <inttypes.h>
#include <avr/interrupt.h>

#include <string.h>


SerialLCD::SerialLCD()
{
  init();
}

void SerialLCD::init()
{
  begin(9600);
}

void SerialLCD::begin(long speed)
{
 
  Serial1.begin(speed);
}

void SerialLCD::setCursor(uint8_t linha, uint8_t coluna)
{
  Serial1.print("@");
  Serial1.print(coluna,  BYTE);
  Serial1.print(linha, BYTE);
  
  delay(8);
}

void SerialLCD::clear()
{
  Serial1.print("[\a]");
  delay(8);
}

void SerialLCD::home()
{
}


void SerialLCD::comando(const char str[]) 
{

}

void SerialLCD::write(const char str[])
{
  Serial1.print("[");
  Serial1.print(str);	
  Serial1.print("]");
  
  delay(8);
}

void SerialLCD::write(const String &s)
{
  Serial1.print("[");
  Serial1.print(s);	
  Serial1.print("]");
  
  delay(8);
}

void SerialLCD::write(long n)
{
  writeNumber(n, 10);
}

void SerialLCD::write(unsigned long n)
{
  writeNumber(n, 10);
}

void SerialLCD::writeNumber(long n, uint8_t base)
{
  unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars. 
  unsigned long i = 0;
  String s = "";
  
  if (n < 0) 
  {
    s = '-';
    n = -n;
  }

  if (n == 0) 
  {
    s = '0';
	
    write(s);
	
    return;
  } 

  while (n > 0) 
  {
    buf[i++] = n % base;
    n /= base;
  }

  for (; i > 0; i--)
    s = s + (char) (buf[i - 1] < 10 ? '0' + buf[i - 1] : 'A' + buf[i - 1] - 10);
	
  write(s);
  
  //write((char) (buf[i - 1] < 10 ? '0' + buf[i - 1] : 'A' + buf[i - 1] - 10));
}

